package me.dwk.dandan.function.functions;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import me.dwk.dandan.function.AbstractFunction;
import me.dwk.dandan.function.CompoundVariable;
import me.dwk.dandan.function.ThreadVariables;
import me.dwk.dandan.function.exception.InvalidVariableException;

/**
 * Provides an intSum function that adds two or more integer values.
 *
 * @see LongSum
 * @since 1.8.1
 */
public class IntSum extends AbstractFunction {
	private static final List<String>	desc	= new LinkedList<>();

	private static final String			KEY		= "__intSum";			//$NON-NLS-1$

	static {
		desc.add("First int to add."); //$NON-NLS-1$
		desc.add("Second int to add - further ints can be summed by adding further arguments."); //$NON-NLS-1$
		desc.add("Name of variable in which to store the result (optional)"); //$NON-NLS-1$
	}

	private Object[] values;

	/**
	 * No-arg constructor.
	 */
	public IntSum() {}

	/** {@inheritDoc} */
	@Override
	public String execute() throws InvalidVariableException {

		ThreadVariables vars = getVariables();

		int sum = 0;
		String varName = ((CompoundVariable) values[values.length - 1]).execute().trim(); // trim() see bug 55871

		for (int i = 0; i < values.length - 1; i++) {
			sum += Integer.parseInt(((CompoundVariable) values[i]).execute());
		}

		try {
			// Has chances to be a var
			sum += Integer.parseInt(varName);
			varName = null; // there is no variable name
		} catch (NumberFormatException ignored) {
			// varName keeps its value and sum has not taken
			// into account non numeric or overflowing number
		}

		String totalString = Integer.toString(sum);
		if (vars != null && varName != null) {// vars will be null on TestPlan
			vars.put(varName.trim(), totalString);
		}

		return totalString;

	}

	/** {@inheritDoc} */
	@Override
	public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
		checkMinParameterCount(parameters, 2);
		values = parameters.toArray();
	}

	/** {@inheritDoc} */
	@Override
	public String getReferenceKey() {
		return KEY;
	}

	/** {@inheritDoc} */
	@Override
	public List<String> getArgumentDesc() {
		return desc;
	}
}
